import { Observable } from 'rxjs/Rx';
import { Http, URLSearchParams } from '@angular/http';
import { EventEmitter, Injectable } from '@angular/core';
import 'rxjs/Rx';

@Injectable()
export class StockService {
  public searchEvent:EventEmitter<StockSearchParams> = new EventEmitter();

  constructor(private http: Http) {
  }

  getStocks(): Observable<Stock[]> {
    return this.http.get('/api/stock').map(result => result.json());
  }

  getStock(id: number): Observable<Stock> {
    return this.http.get('/api/stock/' + id).map(result => result.json());
  }

  search(params: StockSearchParams): Observable<Stock[]> {
    return this.http.get('/api/stock', { search: this.encodeParams(params) }).map(result => result.json());
  }

  private encodeParams(params: StockSearchParams) {
    return Object.keys(params).filter(key => params[key]).reduce((sum: URLSearchParams, key: string) => {
      sum.append(key, params[key]);
      return sum;
    }, new URLSearchParams());
  }

}

export class Stock {
  constructor(public id: number,
    public name: string,
    public price: number,
    public rating: number,
    public desc: string,
    public categories: Array<string>) {
  }
}

export class StockSearchParams {
  constructor(public name: String) {
  }
}
